from gurobipy import *
import gurobipy as gp
import random
try:
    N = 20
    random.seed(1)
    #产生随机Tmatrix和 Cmatrix
    Tmatrix = {(i+1,j+1):random.randint(0,100) for i in range(N) for j in range(N)}
    Cmatrix = {(i+1,j+1):random.randint(0,100) for i in range(N) for j in range(N)}
    #定义model
    m = gp.Model('MultiAssignment')
    #添加变量
    x = m.addVars(Tmatrix.keys(),vtype=GRB.BINARY,name='x')
    #添加约束
    m.addConstrs((x.sum('*',j+1)== 1 for j in range(N)),'c1')
    m.addConstrs((x.sum(i+1,'*')== 1 for i in range(N)),'c2')
    #没置多目标权重
    m.set0bjectiveN( x.prod(Tmatrix),index=0,weight=0.1,name='obj1')
    m.setObjectiveN(-x.prod(Cmatrix),index=1,weight=0.5,name='obj2')
    #设置多目标 优先级
    #m.setObjectiveN( x.prod(Tmatrix),index=0,priority=1,abstol=0,reltol=0,name='obj1')
    #m.setObjectiveN(-x.prod(Cmatrix),index=1,priority=2,abstol=0,reltol=0,name='obj2')

    #设置LogFile的名称
    m.setParam(GRB.Param.LogFile,'MultiAssignmentLog.log')
    #启动求解
    m.optimize()
    #获得求解结果
    for i in Tmatrix.keys():
        if x[i].x>0.9:
            print("工人%d \t ----> \t工作 %d" %(i[0],i[1]))

    for i in range(2):
        m.setParam(GRB.Param.ObjNumber,i)
        print( 'Obj%d =' % (i+1), m.ObjNVal)
    #将model输出到Lp格式文件中
        m.write('MultiAssignment.lp')

except gp.GurobiError as e:
    print('Error code ' + str(e.errno) + ': ' + str(e))

# except AttributeError: #属性错误
#     print('Encountered an attribute error')